<?php 

session_start();

require_once("DatabaseConnect.php"); 
$con=Remoteconnect();
if($con==null){
	$con=Localconnect();	
}

$loggedin=false;
// Report all PHP errors 
error_reporting(E_ALL);
if (!isset($_SESSION['email']))
{
// Check if logged in		
	// check if we came from a form (with email) - 
	if (isset($_POST['email']))  //this could be more robust (check for our specific login form)
	{				
		// Get user's password from database and check if matches with input
		$user = $_POST['email'];
		$sql=mysqli_query($con,"SELECT * FROM  `user` WHERE  `Email` = '$user'");
		
		$row = mysqli_fetch_array($sql);
			if ($row['Password']==$_POST['password'])
			{
				// Set session parameters
				$_SESSION['email'] = $_POST['email'];					
				$_SESSION['s'] =session_id();					
				$cSession = session_id();				
				$sql = "UPDATE user SET Session = '$cSession' WHERE Email = '$user'";
				if (!mysqli_query($con,$sql))
					{
					  $_SESSION['msg'] = "Unable to initialise session";
						header("Location: /Demo");
						
						
					}
				
			}else{
				$_SESSION['msg'] = "Invalid email and/or password1 !";	
					header("Location: /Demo");
				
			}
			
			
			if (isset($_SESSION['email'])){
				$_SESSION['msgG'] = "You are logged in as: ".$_SESSION['email']."";
				header("Location: /Demo");
				$loggedin=true;
				}else{
					$_SESSION['msg'] = "Invalid email and/or password1 !";	
					header("Location: /Demo");
				}
			
			
			

  
	}
		mysqli_close($con);
		
		

		
		// Catches invalid usernames not in database (null query returns)
		if (!isset ($row)& !isset($_SESSION['email'])){
		
				
			$_SESSION['msg'] = "Invalid email and/or password2!";
			header("Location: /Demo");
			
		}
}else{

		$user = $_SESSION['email'];
		$sql=mysqli_query($con,"SELECT * FROM  `user` WHERE  `Email` = '$user'");
		$row = mysqli_fetch_array($sql);
		
		
			if ($row['Session']!=session_id())
			{
	  			
				$_SESSION['msg'] = "You must log in first";
				header("Location: /Demo");
				
			}	
			mysqli_close($con);
			
				
			
	
	
}

?>

